package com.example.main

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.example.R
import com.example.adapter.FragmentAdapter
import com.example.diary.DiaryAddFragment
import com.example.diary.DiaryListFragment
import com.example.mine.MineFragment
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        val diaryListFragment = DiaryListFragment()
        val diaryAddFragment = DiaryAddFragment()
        val mineFragment = MineFragment()
        val fragmentList: MutableList<Fragment> = ArrayList()
        val navigationView: BottomNavigationView = findViewById(R.id.navigationView)
        val viewPager: ViewPager = findViewById(R.id.viewpager)
        fragmentList.add(diaryListFragment)
        fragmentList.add(diaryAddFragment)
        fragmentList.add(mineFragment)
        val fragmentAdapter = FragmentAdapter(fragmentList, supportFragmentManager)
        viewPager.adapter = fragmentAdapter

        // navigationView点击事件监听
        navigationView.setOnNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.menu_diary -> viewPager.currentItem = 0
                R.id.menu_add -> viewPager.currentItem = 1
                R.id.menu_mine -> viewPager.currentItem = 2
            }
            false
        }

        // viewPager滑动事件监听
        viewPager.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {}

            override fun onPageSelected(position: Int) {
                // 将滑动到的页面对应的menu设置为选中状态
                navigationView.menu.getItem(position).isChecked = true
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }
}